package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Component
public class WmTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户id
        String userId = request.getHeader("userId");
        //判断id是否为空
        Optional<String> id = Optional.ofNullable(userId);
        if (id.isPresent()){
            WmUser wmUser=new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            //放入threadlocal中
            WmThreadLocalUtils.setUser(wmUser);
        }
        return true;
    }

    //清理
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        WmThreadLocalUtils.remove();
    }
}
